// 精灵(Sprite) 是一个能通过改变自身的属性：角度，位置，缩放，颜色等，变成可控制动画的 2D 图像。

package sprites

import (
	"github.com/hajimehoshi/ebiten/v2"
)

type Sprite struct {
	img *ebiten.Image // 背板图片
	op  *ebiten.DrawImageOptions

	child []*Sprite // 渲染子结点
}

func NewByWH(width, height int, op *ebiten.DrawImageOptions) *Sprite {
	return &Sprite{
		img:   ebiten.NewImage(width, height),
		op:    op,
		child: []*Sprite{},
	}
}

func NewByImg(img *ebiten.Image, op *ebiten.DrawImageOptions) *Sprite {
	return &Sprite{
		img:   img,
		op:    op,
		child: []*Sprite{},
	}
}

// 增加子结点
func (this *Sprite) AddChild(s *Sprite) *Sprite {
	this.child = append(this.child, s)

	return this
}

// 设置op
func (this *Sprite) SetDrawImageOptions(node *Sprite, op *ebiten.DrawImageOptions) *Sprite {
	this.op = op
	return this
}

func (this *Sprite) Update() error {
	for _, v := range this.child {
		v.Update()
	}

	return nil
}

func (this *Sprite) Draw(screen *ebiten.Image) {
	copy_Img := Clone(this.img, this.op)
	for _, v := range this.child {
		v.Draw(copy_Img)
	}

	screen.DrawImage(copy_Img, this.op)

	defer copy_Img.Dispose()
}

func (this *Sprite) Layout(outsideWidth, outsideHeight int) (int, int) {
	return this.img.Size()
}

// clone
func Clone(pimg *ebiten.Image, op *ebiten.DrawImageOptions) *ebiten.Image {
	w, h := pimg.Size()
	child_img := ebiten.NewImage(w, h)
	child_img.DrawImage(pimg, op)

	return child_img
}
